package net.uhuijia.sys.syssetting.service.impl;


import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.uhuijia.appbase.service.CrudService;
import net.uhuijia.constants.ResponseCode;
import net.uhuijia.sys.syssetting.persistence.dao.SysSettingDao;
import net.uhuijia.sys.syssetting.persistence.model.SysSetting;
import net.uhuijia.sys.syssetting.persistence.model.SysSettingExample;
import net.uhuijia.sys.syssetting.service.SysSettingService;
import net.uhuijia.utils.CalendarHelper;
import net.uhuijia.utils.StringHelper;


@Service
@Transactional
public class SysSettingServiceImpl
     extends CrudService<SysSettingDao,SysSetting,SysSettingExample> 
     implements SysSettingService{
    @Autowired
    private SysSettingDao sysSettingDao;


    public String isOpenPhone(){
    	String isopenPhone = this.getValueByKey("IS_OPEN_PHONE_CODE");
    	return isopenPhone;
    }
    
    public String getValueByKey(String key) {
    	String result = "";
    	//首先从数据库里取
    	SysSetting byKey = sysSettingDao.getByKey(key);
    	if( null != byKey ){
    		result = byKey.getSysValue();
    	}
		return result;
	}
    
    /**
     * 获取 验证码的过期 时间
     * @param date
     * @return
     */
    public Date getExpiredTimeCode(Date date){
    	String minuteStr = "5";//默认CODE有效期为5分
    	String minuteSet = this.getValueByKey("CODE_EXPIRED_MINUTE");
    	if( StringHelper.isNotBlank(minuteSet) ){
    		minuteStr = minuteSet;
    	}
    	Date dateAfter = CalendarHelper.getMinuteAfter(date, Integer.parseInt(minuteStr));
    	return dateAfter;
    }
    
    /**
     * 获取 Token的过期 时间
     * @param date
     * @return
     */
    public Date getExpiredTimeToken(Date date){
    	String dayStr = "7";//默认TOKEN有效期为7天
    	String daySet = this.getValueByKey("TOKEN_EXPIRED_DAY");
    	if( StringHelper.isNotBlank(daySet) ){
    		dayStr = daySet;
    	}
    	Date dateAfter = CalendarHelper.getDateAfter(date, Integer.parseInt(dayStr));
    	return dateAfter;
    }

	@Override
	public SysSetting getObjectByKey(String key) {
		return sysSettingDao.getByKey(key);
	}

	@Override
	public String setValueByKey(String key, String value) {
		SysSetting sysSetting = this.getObjectByKey(key);
		if( null != sysSetting ){
		    sysSetting.setSysValue(value);
		    this.edit(sysSetting);
		}else{
			sysSetting = new SysSetting();
			sysSetting.setSysValue(value);
			this.add(sysSetting);
		}
        return ResponseCode.SUCCESS.getCode();
	}
}